/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package quickpusher;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.Socket;
import javax.swing.JOptionPane;

/**
 * @author Filip
 */
public class QuickSender{

    private static File saveFile = new File(System.getenv("APPDATA"),"SimplePushIP.ini");
    public static void main(String[] args){
        String ip = "ip";
        int port = 0;
        String data= "data";
        for(String s : args){
            System.out.println(s);
        }
        try{
            if(args[0].contains("*") && args[1].contains("*")){
                String[] adress = loadAdress().split(":");
                ip = adress[0];
                port = Integer.parseInt(adress[1]);
            }else{
                ip = args[0];
                port = Integer.parseInt(args[1]);
            }
            data = args[2];
            int i = 3;
            while(i<args.length){
                data+=args[i];
                i++;
            }

            if(data.contains("play:") || data.contains("spotifymusik:")){
                data="play:"+new File(data.replace('/','\\')).getName();
            }else if(data.contains("enqueue:")){
                data="enqueue:"+new File(data.replace('/','\\')).getName();
            }
            Socket s = new Socket(ip, port);
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            if (!(data == null || data.isEmpty())) {
                dos.writeUTF(data);
            }
            s.close();
        }catch (Exception ce) {
            p("Remote computer isn't online or the connect was "
                +"blocked by a firewall\n\n"+ce.toString()
                +"\nServer: "+ip.toString()+" @ port: "+port+"\nData: "+data);
        }
    }
    private static void p(String toString) {
        JOptionPane.showMessageDialog(null, toString);
    }
    public static String loadAdress() throws FileNotFoundException, IOException{
        BufferedReader br = new BufferedReader(new FileReader(saveFile));
        String s = "";
        int cha=0;
        while(true){
            cha = br.read();
            if(cha!=-1){
                s+=(char)cha;
            }else{
                break;
            }
        }
        br.close();
        return s.trim();
    }
}